//
//  UserPresenter.m
//  MVP4
//
//  Created by 李煜 on 2024/6/21.
//

#import "UserPresenter.h"

@interface UserPresenter()

@property (nonatomic, strong) UserService *userService;
@property (nonatomic, weak) id<UserView> userView;

@end

@implementation UserPresenter

- (instancetype)initWithUserService:(UserService *)userService {
    if (self = [super init]) {
        self.userService = userService;
    }
    return self;
}

- (void)attachView:(id<UserView>)view {
    _userView = view;
}

- (void)detachView {
    _userView = nil;
}

- (void)getUsers {
    [_userView startLoading];
    __weak typeof(self) weakSelf = self;
    [_userService getUsers:^(NSArray<User *> *users){
        [weakSelf.userView finishLoading];
        if (users.count == 0) {
            [weakSelf.userView setEmptyUsers];
        } else {
            NSMutableArray *userArray = [NSMutableArray array];
            for(User *user in users) {
                UserViewData *userData = [[UserViewData alloc] init];
                userData.name = [NSString stringWithFormat:@"%@ %@", user.firstName, user.lastName];
                userData.age = [NSString stringWithFormat:@"%d years", user.age];
                [userArray addObject:userData];
            }
            [weakSelf.userView setUsers:userArray];
        }
    }];
}

@end
